package com.lxmes.device.service.impl;

import com.lxmes.common.annotation.DataScope;
import com.lxmes.common.core.domain.entity.SysDept;
import com.lxmes.common.exception.ServiceException;
import com.lxmes.common.utils.DateUtils;
import com.lxmes.common.utils.NewNumber;
import com.lxmes.common.utils.SecurityUtils;
import com.lxmes.common.utils.StringUtils;
import com.lxmes.common.utils.bean.BeanValidators;
import com.lxmes.device.domain.Device;
import com.lxmes.device.mapper.DeviceMapper;
import com.lxmes.device.service.IDeviceService;
import com.lxmes.device.utils.QRCodeUtils;
import com.lxmes.framework.config.ServerConfig;
import com.lxmes.system.service.ISysDeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.util.Date;
import java.util.List;

/**
 * 设备列表Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-04-13
 */
@Service
public class DeviceServiceImpl implements IDeviceService 
{
    private static final Logger log = LoggerFactory.getLogger(DeviceServiceImpl.class);

    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ISysDeptService deptService;

    /**
     * 查询设备列表
     * 
     * @param deviceId 设备列表主键
     * @return 设备列表
     */
    @Override
    public Device selectDeviceByDeviceId(Long deviceId)
    {
        return deviceMapper.selectDeviceByDeviceId(deviceId);
    }
    /**
     * 查询设备列表
     *
     * @param deviceCode 设备编码
     * @return 设备列表
     */
    @Override
    public Device selectDeviceByDeviceCode(String deviceCode) {

        return deviceMapper.selectDeviceByDeviceCode(deviceCode);
    }

    /**
     * 查询设备列表列表
     * 
     * @param device 设备列表
     * @return 设备列表
     */
    @Override
    @DataScope(deptAlias = "de", userAlias = "de")
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    @Override
    @DataScope(deptAlias = "de", userAlias = "de")
    public List<Device> selectDeviceApiList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备列表
     * 
     * @param device 设备列表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) throws Exception {
        String number= NewNumber.createNewNumber(deviceMapper.getNewCode(DateUtils.getDate()));
        device.setDeviceCode("TKSB"+number);
        //device.setDeviceCode("SBBM-"+DateUtils.dateTimeNow());
        validEntityBeforeSaveOrUpdate(device);
        String loginImg=StringUtils.isNotEmpty(device.getDeviceImg())?device.getDeviceImg().split(",")[0]:null;
        device.setDeviceEwm( QRCodeUtils.getEwmUrl(device.getDeviceCode(),loginImg));
        //使用部门
        if(StringUtils.isNotNull(device.getDeptId())){
            SysDept dept = deptService.selectDeptById(device.getDeptId());
            if(StringUtils.isNotNull(dept)){
                device.setUseDept(dept.getDeptName());
            }else {
                throw new ServiceException("使用部门不存在");
            }
        }else {
            device.setDeptId(SecurityUtils.getDeptId());
            SysDept dept = deptService.selectDeptById(device.getDeptId());
            device.setUseDept(dept.getDeptName());
        }
        device.setUserId(SecurityUtils.getUserId());
        device.setCreateTime(DateUtils.getNowDate());
        return deviceMapper.insertDevice(device);
    }

    /**
     * 修改设备列表
     * 
     * @param device 设备列表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) throws Exception {
       /* String destPath = RuoYiConfig.getUploadPath();
        String logoPath=null;
        String text = "http://www.baidu.com";  //这里设置自定义网站url
        if(StringUtils.isNotEmpty(device.getDeviceImg())){
            String[] img = device.getDeviceImg().split(",");
            logoPath=destPath+img[0];
            int dirLastIndex = "/profile/upload".length();
            System.out.println(dirLastIndex);
            String currentDir = StringUtils.substring(img[0], dirLastIndex);
            System.out.println(currentDir);
            logoPath=destPath+currentDir;
        }
        String fileName= QRCodeUtils.encode(text, logoPath, destPath, true);
       String newFileName =FileUploadUtils.getPathFileName(destPath, fileName);*/
        String loginImg=StringUtils.isNotEmpty(device.getDeviceImg())?device.getDeviceImg().split(",")[0]:null;
        device.setDeviceEwm( QRCodeUtils.getEwmUrl(device.getDeviceCode(),loginImg));
        device.setUpdateTime(DateUtils.getNowDate());
        validEntityBeforeSaveOrUpdate(device);
        //使用部门
        if(StringUtils.isNotNull(device.getDeptId())){
            SysDept dept = deptService.selectDeptById(device.getDeptId());
            if(StringUtils.isNotNull(dept)){
                device.setUseDept(dept.getDeptName());
            }else {
                throw new ServiceException("使用部门不存在");
            }
        }else {
            device.setDeptId(SecurityUtils.getDeptId());
            SysDept dept = deptService.selectDeptById(device.getDeptId());
            device.setUseDept(dept.getDeptName());
        }
        return deviceMapper.updateDevice(device);
    }
    public void  validEntityBeforeSaveOrUpdate(Device device){
        int v=deviceMapper.validEntityBeforeSaveOrUpdate(device);
        if(v>0){
            throw new ServiceException("设备编码"+device.getDeviceCode()+"已存在");
        }

    }
    /**
     * 批量删除设备列表
     * 
     * @param deviceIds 需要删除的设备列表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByDeviceIds(Long[] deviceIds)
    {
        return deviceMapper.deleteDeviceByDeviceIds(deviceIds);
    }

    /**
     * 删除设备列表信息
     * 
     * @param deviceId 设备列表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByDeviceId(Long deviceId)
    {
        return deviceMapper.deleteDeviceByDeviceId(deviceId);
    }
     /*批量重新生成二维码*/
    @Override
    public int createDeviceEwm(Long[] deviceIds) throws Exception {
        for (int i = 0; i <deviceIds.length ; i++) {
            Device device = deviceMapper.selectDeviceByDeviceId(deviceIds[i]);
            String loginImg=StringUtils.isNotEmpty(device.getDeviceImg())?device.getDeviceImg().split(",")[0]:null;
            device.setDeviceEwm( QRCodeUtils.getEwmUrl(device.getDeviceCode(),loginImg));
             deviceMapper.updateDevice(device);
        }
        return 1;
    }

    /**
     * 导入设备数据
     *
     * @param deviceList 设备数据数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importDevice(List<Device> deviceList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(deviceList) || deviceList.size() == 0)
        {
            throw new ServiceException("导入设备数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Device device : deviceList)
        {
            try
            {
                String number= NewNumber.createNewNumber(deviceMapper.getNewCode(DateUtils.getDate()));
                device.setDeviceCode("TKSB"+number);
                // 验证是否存在这个用户
                int d = deviceMapper.validEntityBeforeSaveOrUpdate(device);
                if (d==0)
                {
                    BeanValidators.validateWithException(validator, device);
                    device.setCreateBy(operName);
                    device.setCreateTime(new Date());
                    device.setDeptId(SecurityUtils.getDeptId());
                    String loginImg=StringUtils.isNotEmpty(device.getDeviceImg())?device.getDeviceImg().split(",")[0]:null;
                    device.setDeviceEwm( QRCodeUtils.getEwmUrl(device.getDeviceCode(),loginImg));
                    this.insertDevice(device);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、设备编码 " + device.getDeviceCode() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, device);
                    this.updateDevice(device);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、设备编码 " + device.getDeviceCode() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、设备编码 " +device.getDeviceCode() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、设备编码 " + device.getDeviceCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
